﻿using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using Microsoft.WindowsAzure.Storage.Table.DataServices;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Wams.Admin;

namespace Wams.Server
{
    public class WamsSiteState : TableEntity
    {
        public WamsSiteState(string deploymentInstanceId, int siteId)
        {
            this.PartitionKey = deploymentInstanceId;
            this.RowKey = siteId.ToString();
        }

        public WamsSiteState() { }

        public DateTime? LastContentSync { get; set; }
        public DateTime? LastSettingsSync { get; set; }
        public int InnerStatus { get; set; }
        public SiteStatus Status 
        { 
            get
            {
                return (SiteStatus)InnerStatus;
            }
            set
            {
                InnerStatus = (int)value;
                Save();
            }
        }

        private static string GetTableName()
        {
            return WamsCore.ContainerName + "sites";
        }
        public void Save()
        {
            CloudTableClient tableClient = WamsCore.MainStorageAccount.CreateCloudTableClient();

            CloudTable table = tableClient.GetTableReference(GetTableName());
            table.CreateIfNotExists();

            TableOperation retrieveOperation = TableOperation.Retrieve<WamsSiteState>(this.PartitionKey, this.RowKey);

            TableResult retrievedResult = table.Execute(retrieveOperation);

            WamsSiteState specificEntity = (WamsSiteState)retrievedResult.Result;
            TableOperation tOp = null;
            if (specificEntity != null)
            {
                specificEntity.InnerStatus = (int)this.Status;
                specificEntity.LastContentSync = this.LastContentSync;
                specificEntity.LastSettingsSync = this.LastSettingsSync;
                specificEntity.ETag = "*";
                tOp = TableOperation.Replace(specificEntity);
            }
            else tOp = TableOperation.Insert(this);
            
            table.Execute(tOp);

        }

        public void Refresh()
        {
            CloudTableClient tableClient = WamsCore.MainStorageAccount.CreateCloudTableClient();

            CloudTable table = tableClient.GetTableReference(GetTableName());
            table.CreateIfNotExists();

            TableOperation retrieveOperation = TableOperation.Retrieve<WamsSiteState>(this.PartitionKey, this.RowKey);

            TableResult retrievedResult = table.Execute(retrieveOperation);

            WamsSiteState specificEntity = (WamsSiteState)retrievedResult.Result;
            
            if (specificEntity == null) return;
            InnerStatus = (int)specificEntity.Status;
        }

        public void Delete()
        {
            CloudTableClient tableClient = WamsCore.MainStorageAccount.CreateCloudTableClient();

            CloudTable table = tableClient.GetTableReference(GetTableName());
            table.CreateIfNotExists();

            TableOperation retrieveOperation = TableOperation.Retrieve<WamsSiteState>(this.PartitionKey, this.RowKey);

            TableResult retrievedResult = table.Execute(retrieveOperation);

            WamsSiteState specificEntity = (WamsSiteState)retrievedResult.Result;

            if (specificEntity == null) return;

            TableOperation deleteOp = TableOperation.Delete(specificEntity);
            table.Execute(deleteOp);
        }


        public static void DeleteExpired()
        {
            CloudTableClient tableClient = WamsCore.MainStorageAccount.CreateCloudTableClient();

            CloudTable table = tableClient.GetTableReference(GetTableName());
            TableServiceContext tableServiceContext = table.ServiceClient.GetTableServiceContext();
            IQueryable<WamsSiteState> q = (from state in tableServiceContext.CreateQuery<WamsSiteState>(GetTableName())
                                               select state);

            foreach (WamsSiteState state in q)
            {
                if (state.Timestamp >= DateTime.UtcNow.AddMinutes(-2)) continue;
                state.ETag = "*";
                TableOperation deleteOp = TableOperation.Delete(state);
                table.Execute(deleteOp);
            }
        }
        
    }
}